<template>
  <!-- <div class="flex h-full w-full flex-col overflow-hidden">
    <div class="title">
      <span>实时波形数据</span>
    </div>
    <div class="flex flex-1 px-8">
      <div class="info w-48">
        <div class="info-item">
          <div class="info-item_header">
            <PieChartFilled />
            <span>数据展示</span>
          </div>
          <div class="info-item_content">
            <RadioGroup v-model:value="isHighPassFilter">
              <Radio :style="radioStyle" :value="false">原始数据</Radio>
              <Radio :style="radioStyle" :value="true">高通滤波</Radio>
            </RadioGroup>
          </div>
        </div>
        <div class="info-item">
          <div class="info-item_header">
            <TagFilled />
            <span>数据类型</span>
          </div>
          <div class="info-item_content">
            <p><CalendarFilled /> <span>加速度</span></p>
          </div>
        </div>
        <div class="info-item">
          <div class="info-item_header">
            <BoxPlotFilled />
            <span>通道</span>
          </div>
          <div class="info-item_content">
            <div
              v-for="(item, index) in channels"
              :key="index"
              class="flex items-center"
            >
              <Checkbox v-model:checked="item.checked" />
              <span class="w-18 mx-2">{{ item.name }}-{{ item.des }}</span>
              <div
                class="h-4 w-4"
                :style="{ backgroundColor: item.color }"
              ></div>
            </div>
          </div>
        </div>
        <div class="info-item">
          <div class="info-item_header">
            <SlidersFilled />
            <span>设备</span>
          </div>
          <div class="info-item_content">
            <p>
              <CalendarFilled />
              <span>{{ code }}</span>
            </p>
          </div>
        </div>
      </div>
      <div class="flex-1 overflow-hidden">
        <div class="h-full w-full bg-[#103B62]" :id="id"></div>
      </div>
    </div>
  </div> -->

  <TriggerData title="实时数据波形" :options="options" @change="console.log">
    <template #header></template>
    <template #customRender="{ channel, presentation }">
      <div class="h-full w-full bg-[#103B62]" :id="id"></div>
    </template>
  </TriggerData>
</template>

<script setup lang="tsx">
import { onMounted, reactive, ref, toRaw, toValue, useId, watch } from 'vue';
import { realDataChart } from '@/utils';
import {
  BoxPlotFilled,
  CalendarFilled,
  PieChartFilled,
  SlidersFilled,
  TagFilled,
} from '@ant-design/icons-vue';
import { useEventSource } from '@boeyo/hooks';
import { useUserStore } from '@boeyo/portal';
import { Checkbox, Radio, RadioGroup } from 'ant-design-vue';
import TriggerData from '@/components/triggerData/index.vue';
import { HighPassFilter } from './HighPassFilter';

const hpFilter = new HighPassFilter(1, 100);

interface Props {
  /** 设备标识 */
  code: string;
  /** 格值 */
  latticeValue?: number;
  /** 烈度 */
  intensity?: number;
  /** 采样率 */
  samplingRate?: number;
}
const {
  code,
  latticeValue = 500,
  intensity = 1,
  samplingRate = 100,
} = defineProps<Props>();

const radioStyle = reactive({
  display: 'flex',
  height: '30px',
  lineHeight: '30px',
});

const options = reactive({
  presentationList: [
    {
      label: '原始数据',
      value: 'value',
      disabled: false,
    },
    {
      label: '高通滤波',
      value: 'log',
      disabled: false,
    },
  ],
  dataTypeList: [
    {
      label: '加速度',
      value: 'accelerationData',
      disabled: false,
    },
  ],
  channelList: [
    {
      value: 'EIZ',
      label: 'EIZ-竖桥向',
      color: '#F16995',
    },
    {
      value: 'EIN',
      label: 'EIN-横桥向',
      color: '#77E3F9',
    },
    {
      value: 'EIE',
      label: 'EIE-纵桥向',
      color: '#DFC428',
    },
  ],
  deviceInfoList: [
    {
      label: 'WH.W1875',
      value: 'WH.W1875',
      disabled: false,
    },
  ],
});

const channels = reactive([
  {
    name: 'EIZ',
    des: '竖桥向',
    color: '#F16995',
    yName: '单位: 度(°)',
    checked: true,
  },
  {
    name: 'EIN',
    des: '横桥向',
    color: '#77E3F9',
    yName: '单位: 度(°)',
    checked: true,
  },
  {
    name: 'EIE',
    des: '纵桥向',
    color: '#DFC428',
    yName: '单位: 度(°)',
    checked: true,
  },
]);

const isHighPassFilter = ref(false);
const id = useId();

const userStore = useUserStore();

let renderChart;
let updateChartConfig;

const init = () => {
  const { renderChart: _renderChart, updateChartConfig: _updateChartConfig } =
    realDataChart({
      target: document.getElementById(id),
      title: `设备标识：${code} | 采样率：${samplingRate} | 烈度：${intensity}`,
      direction: 'vertical',
      channels: toRaw(channels),
    });
  renderChart = _renderChart;
  updateChartConfig = _updateChartConfig;
};

onMounted(() => {
  init();
});

watch(
  () => channels,
  () => {
    updateChartConfig(
      toRaw(channels)
        .filter((item) => item.checked)
        .map((cur, index) => {
          return {
            ...cur,
            grid: {
              show: true,
              top: `${30 * index + 5} + %`,
              left: '7%',
              right: '3%',
              height: `${100 / 3 - 10}%`,
              containLabel: true,
            },
          };
        }),
    );
  },
  { deep: true },
);

const formatData = (cb) => {
  let data = {};
  const checkData = () => {
    let flag = false;
    if (Object.keys(data).length !== 3) return false;
    Object.values(data)
      .map((item) => item[0][0])
      .reduce((prev, cur) => {
        flag = prev === cur;
        return cur;
      });
    return flag;
  };
  const push = (_data) => {
    Object.keys(_data).forEach((_key) => {
      let key;
      switch (_key) {
        case 'Z':
          key = 'EIZ';
          break;
        case 'N':
          key = 'EIN';
          break;
        case 'E':
          key = 'EIE';
          break;
        default:
          break;
      }
      if (_key !== 'X') {
        data[key] = _data[_key];
      }
    });
    if (checkData()) {
      cb(data);
      data = {};
    }
  };
  return push;
};

const push = formatData((data) => {
  const dataSource = {};
  for (const key in data) {
    if (Object.prototype.hasOwnProperty.call(data, key)) {
      const element = data[key];

      dataSource[key] = element.reduce((prev, cur) => {
        if (cur[0] % 100 === 0) {
          let value = cur[1];
          if (isHighPassFilter.value) {
            value = hpFilter.filter(value);
          }
          cur[1] = cur[1];

          prev.push(cur);
        }

        return prev;
      }, []);
    }
  }
  renderChart(dataSource);
});

const random = Math.random().toString().slice(-6);
const { connect, disconnect } = useEventSource(
  `/api/edge/sse/300/${random}/${code}`,
  {
    headers: {
      ['Authorization']: `Bearer ${userStore.token}`,
      'Content-Type': 'application/json',
      Accept: '*/*',
    },
    withCredentials: false,
    onMessage(res) {
      const data = JSON.parse(res);
      push(data);
    },
    onError(error) {
      console.log(error);
      disconnect();
    },
  },
);

onMounted(() => {
  connect();
});
</script>

<style lang="scss" scoped>
.title {
  color: #fff;
  text-align: center;
  height: 68px;
  background: url('/static/chart/chart-title.png') no-repeat center/ cover;

  span {
    font-size: 32px;
    font-weight: bold;
    background: linear-gradient(180deg, #ffffff 26%, #93d5ff 100%);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
  }
}

.info {
  width: 248px;

  .info-item {
    margin-bottom: 16px;

    &_header {
      width: 100%;
      height: 30px;
      font-size: 18px;
      background: #235691;
      padding: 0 8px;
      span {
        margin-left: 8px;
        font-size: 14px;
      }
    }

    &_content {
      padding: 10px 14px;
      background: linear-gradient(
        180deg,
        rgba(55, 117, 198, 0) 0%,
        rgba(55, 117, 198, 0.4) 100%
      );

      p {
        font-size: 14px;
        span {
          margin-left: 8px;
        }
      }
    }
  }
}
</style>
